using System;
using System.Collections.Generic;
using System.Text;

namespace Lib.Integration
{
    public class IntegrateDataFromFlatToSql
    {
        string splitter = "";
        string[] FieldList;
        string[] ValueList;
        string SQLColumnList = "";
        string _siteName = "";
        string SQLTable = "";
        string DBConnectionString = "";
        System.Collections.Queue st = new System.Collections.Queue();
        System.Collections.Queue fst = new System.Collections.Queue();

        public int InQueu { get { return st.Count; } }

        public void IntegrateFlatToSQL(string Separator, string siteName, string[] Algorithm, string toTable, string connectionString)
        {
            DBConnectionString = connectionString;
            FieldList = new string[Algorithm.Length];
            ProcessAlgorithm(Algorithm);
            SQLTable = toTable;
            splitter = Separator;
            _siteName = siteName;
            string[] FileName = Utilities.FileUtility.GetListFileNames(AppDomain.CurrentDomain.BaseDirectory + "\\Files\\Processed\\" + _siteName + "\\",true).Split(',');
            foreach (string f in FileName)
            {
                if (!string.IsNullOrEmpty(f))
                {
                    fst.Enqueue(f);
                    System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ProcessFile), Separator);
                }
            }
        }

        void ProcessAlgorithm(string[] Alg)
        {
            int n = 0;
            foreach(string algorithm in Alg)
            {
                if (algorithm.IndexOf("=") >= 0)
                {
                    string[] algDivide = algorithm.Split(new char[] { '=' });
                    
                    if (!string.IsNullOrEmpty(algDivide[0].Trim()) && !string.IsNullOrEmpty(algDivide[1].Trim()))
                    {
                        SQLColumnList += "," + algDivide[1];
                        FieldList[n] = algDivide[0];
                    }
                }
                n++;
            }
            if (!string.IsNullOrEmpty(SQLColumnList))
                if (SQLColumnList.StartsWith(","))
                    SQLColumnList = SQLColumnList.Remove(0, 1);
            int j = 0;
                for (int i = 0; i < FieldList.Length; i++)
                {
                    if (string.IsNullOrEmpty(FieldList[i]))
                    {
                        for (int k = i + 1; k < FieldList.Length; k++)
                            FieldList[k - 1] = FieldList[k];
                        i--;
                        j++;
                    }
                }
                if (j > 0)
                {
                    string[] tempList = new string[FieldList.Length - j];
                    Array.Copy(FieldList, 0, tempList, 0, FieldList.Length - j);
                    FieldList = tempList;
                }
        }

        void ProcessFile(object obj)
        {
            if (fst.Count > 0)
            {
                string FileName = (string)fst.Dequeue();
                if (!string.IsNullOrEmpty(FileName))
                {
                    //st.Enqueue(Utilities.FileUtility.GetFileContent(FileName, true));
                    st.Enqueue(Utilities.FileUtility.GetFileContent(FileName, false));
                    System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ProcessData));
                }
            }
        }

        void ProcessData(object obj)
        {
            string Content = (string)st.Dequeue();
            if (string.IsNullOrEmpty(Content))
                return;
            string[] ContentLine = Content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            string[] fieldListArr = ContentLine[0].Split(new string[] { splitter }, StringSplitOptions.RemoveEmptyEntries);
            string[] contentArr = ContentLine[1].Split(new string[] { splitter }, StringSplitOptions.RemoveEmptyEntries);
            ValueList = new string[FieldList.Length];
            for(int i=0; i<FieldList.Length; i++)
            {
                string s = FieldList[i];
                if (s.IndexOf("+") < 0)
                {
                    int ind = Array.IndexOf(fieldListArr, s);
                    if (ind >= 0)
                        ValueList[i] = contentArr[ind].Trim();
                }
                else
                {
                    string[] lstFields = s.Split(new char[] { '+' });
                    foreach (string str in lstFields)
                        if (!string.IsNullOrEmpty(str.Trim()))
                        {
                            int ind = Array.IndexOf(fieldListArr, str.Trim());
                            if (ind >= 0)
                                ValueList[i] += contentArr[ind].Trim();
                        }
                }
            }
            System.Threading.ThreadPool.SetMaxThreads(10, 20);
            Utilities.DatabaseUtility dbUtil = new Lib.Utilities.DatabaseUtility(DBConnectionString);
            dbUtil.InsertData(SQLTable, SQLColumnList, ValueList);
        }
    }
}